/**
 * 
 */
package de.akad.imp03.timer;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JLabel;

/**
 * Verwaltung der Restzeit
 * 
 * @author wolfgang
 *
 */
public class TimeModel {
	final public static int INTERVALL = 1; // in Sekunden
	final public static int START = 15; // in Sekunden
	
	private int restzeit = START; // in Sekunden
	private Timer timer;
	
	private List<JLabel> changedListener = new ArrayList<JLabel>();
	private List<JLabel> finishedListener = new ArrayList<JLabel>();
	
	public void decrement() {
		restzeit -= INTERVALL;
		fireChangedEvent();
	}
	
	public String getRestzeitAsString() {
		int sec = restzeit % 60;
		int min = (restzeit - sec) / 60;
		String minString = "00" + min;
		String secString = "00" + sec;
		return minString.substring(minString.length() - 2, minString.length())
				+ ":" + secString.substring(secString.length() - 2, secString.length());
	}
	
	
	/**
	 * @param label sollte besser ein eigenes Interface mit Callback-Methode sein
	 */
	public void addChangedListener(JLabel label) {
		changedListener.add(label);
	}

	public void addFinishedListener(JLabel label) {
		finishedListener.add(label);
	}
	
	public void fireChangedEvent() {
		for (JLabel each: changedListener) {
			// Bei besserer Entkopplung ruft man hier die Callback-Methode eines Interfaces auf
			each.setText(getRestzeitAsString());
		}
		if (restzeit <= 0) {
			timer.cancel();
			fireFinishedEvent();
		}
	}

	public void fireFinishedEvent() {
		for (JLabel each: finishedListener) {
			each.setText("Fertig!");
		}
	}

	public void startTimer() {
		
		TimerTask task = new TimerTask() {
			
			@Override
			public void run() {
				TimeModel.this.decrement();
			}
		};
		
	    timer = new Timer();
	    // sofort starten, dann jede Sekunde wiederholen, alle Angaben in Millisekunden
	    timer.schedule(task, 0, TimeModel.INTERVALL * 1000);

	}


}
